<?php
namespace app\api\controller\v1;
use think\Db;
use app\service\CouponService;
class Coupon extends Base
{
	public function _initialize()
	{
		parent::_initialize();
		$this->IsLogin(); //验证登录
	}

	/**
	 * 获取优惠券列表
	 */
	public function lists()
	{
		//优惠券过期处理
		CouponService::CouponUserExpireHandle();
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
		//表单验证
		$validate = $this->validate(
			$params,
			[
				'status' => 'require',
				'page' => 'require'
			],
			[
				'status.require' => '状态有误',
				'page.require' => '分页有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        $map = [
        	'user_id' => $params['user']['id'],
        ];
        switch ($params['status']) {
        	//待使用
			case 1:
			    $map['is_valid'] = 1;
			    $map['is_expire'] = 0;
			    $map['is_use'] = 0;
			break;
			//已使用
			case 2:
				$map['is_use'] = 1;
			break;
			//已过期
			case 3:
				$map['is_expire'] = 1;
			break;
        }
        $list_data = Db::name('coupon_user')->where($map)->order('id desc')->limit(($params['page']-1)*10,10)->select();
        if(!empty($list_data))
        {
        	//优惠券类型
        	$coupon_type_array = CouponService::$coupon_type_array;
        	//遍历处理
        	foreach($list_data as $key => $value)
        	{
        		if($value['is_valid'] == 1 && $value['is_expire'] == 0 && $value['is_use'] == 0)
        		{
        			$list_data[$key]['is_operable'] = 1;
        		}else
        		{
        			$list_data[$key]['is_operable'] = 0;
        		}
        		//优惠券类型
        		$list_data[$key]['coupon_type_name'] = !empty($coupon_type_array[$value['coupon_type']]['name']) ? $coupon_type_array[$value['coupon_type']]['name'] : '';
        		//有效期
        		$list_data[$key]['time_end_time'] = !empty($value['time_end']) ? date('Y/m/d H:i', $value['time_end']) : '';
        	}
        	$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $list_data;
        }else
        {
        	$result['code'] = -1;
	        $result['msg'] = "暂无数据";
        }
        echo json_encode($result);
	}
}